package net.sf.nlp.segment;

import java.io.InputStream;

import net.sf.nlp.segment.util.Utility;


public class ContextStat 
{
	private int totalFreq;// The total number of all the tags
	private int[] symbolTable;
	private int[] tagFreq;// The total number a tag appears
	private int[][] contextArray;// The context array
	
	public ContextStat(String contextFileName)
	{
		load(getClass().getResourceAsStream(contextFileName));
	}
	
	public void load(InputStream is)
	{
		try
		{
			long length = Utility.getLong(is);
			
			symbolTable = new int[(int)length]; 
			tagFreq = new int[(int)length]; 
			contextArray = new int[(int)length][(int)length]; 
			
			
			for (int i = 0; i < length; i++) 
			    symbolTable[i] = (int)Utility.getLong(is);
		    
			Utility.getLong(is);
			
			totalFreq = (int)Utility.getLong(is);
			
			for (int i = 0; i < length; i++) 
				tagFreq[i] = (int)Utility.getLong(is);
			
			for (int i = 0; i < length; i++) 
			{
				for (int j = 0; j < length; j++) 
					contextArray[i][j] = (int)Utility.getLong(is);
		    }
			
			is.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public long getFreq(long tag) 
	{
		int index = Utility.binarySearch((int)tag, symbolTable);
		if (index == -1)
			return 0;
		
		return tagFreq[index];
	}
	
	public double getPossibility(int prev, int cur) 
	{
		double result = 0;
		int curIndex = Utility.binarySearch(cur, symbolTable);
		int prevIndex = Utility.binarySearch(prev, symbolTable);
		
		if (curIndex == -1 || prevIndex == -1)
			return 0.000001;
		
		int prevCurConFreq = contextArray[prevIndex][curIndex];
		int prevFreq = tagFreq[prevIndex];
		
	    if (prevCurConFreq == 0 || prevFreq == 0)
	    	return 0.000001;
	    
		// 0.9 and 0.1 is a value based experience
		result = 0.9 * (double) prevCurConFreq;
		result /= (double) prevFreq;
		result += 0.1 * (double) prevFreq / (double) totalFreq;
		
		return result;
	}
}
